﻿using SuperSocket.SocketBase.Command;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SSServer.Command
{
    public class CMD_0005_UpFile : CommandBase<MySession, MyRequestInfo>
    {
        private int Action = 5;
        public override string Name
        {
            get { return Action.ToString(); }
        }
        private   string AssemblyDirectory
        {
            get
            {
                string codeBase = Assembly.GetExecutingAssembly().CodeBase;
                UriBuilder uri = new UriBuilder(codeBase);
                string path = Uri.UnescapeDataString(uri.Path);
                FileInfo info = new FileInfo(path);
                path = info.DirectoryName;
                path = path + @"\temp";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                return path;
            }
        }
        /// <summary>
        /// 上行
        /// </summary>
        public override void ExecuteCommand(MySession session, MyRequestInfo requestInfo)
        {
            string fileName = string.Format("{0}\\{1}", this.AssemblyDirectory, DateTime.Now.ToString("yyyy-MM-dd") +  Guid.NewGuid().ToString("N"));
            using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
            {
                try
                {
                    fs.Write(requestInfo.Data, 0, requestInfo.Data.Length);
                    
                    LogHelper.WriteLog(session.NickName + " " + requestInfo.Body);
                    Push(session, "已收到文件");
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(session.NickName + " " + ex);
                    Push(session, "收到文件,但服务端发生了异常");
                }
                finally
                {
                    fs.Close();
                    fs.Dispose();
                }
                
            }

          
        }

        /// <summary>
        ///  下行(推送)
        /// </summary>
        public void Push(MySession session, string text)
        {
            var response = BitConverter.GetBytes((ushort)Action).Reverse().ToList();
            var arr = System.Text.Encoding.UTF8.GetBytes(text);
            response.AddRange(BitConverter.GetBytes((ushort)arr.Length).Reverse().ToArray());
            response.AddRange(arr);

            session.Send(response.ToArray(), 0, response.Count);
        }

    }

}
